﻿Public Class ComparaString
    Inherits System.Web.UI.Page

    ''' <summary>
    ''' Compara duas strings baseado em seus pares de letras
    ''' </summary>
    ''' <param name="str1"></param>
    ''' <param name="str2"></param>
    ''' <returns>A porcentagem de semelhança</returns>
    Public Function CompareStrings(str1 As String, str2 As String) As Double
        Dim pairs1 As List(Of String) = WordLetterPairs(str1.ToUpper())
        Dim pairs2 As List(Of String) = WordLetterPairs(str2.ToUpper())

        Dim intersection As Integer = 0
        Dim union As Integer = pairs1.Count + pairs2.Count

        For i As Integer = 0 To pairs1.Count - 1
            For j As Integer = 0 To pairs2.Count - 1
                If pairs1(i) = pairs2(j) Then
                    intersection += 1
                    pairs2.RemoveAt(j)
                    Exit For
                End If
            Next
        Next

        Return (2.0 * intersection) / union
    End Function

    Private Function WordLetterPairs(str As String) As List(Of String)
        Dim AllPairs As New List(Of String)()
        Dim Words As String() = Regex.Split(str, "\s")

        For w As Integer = 0 To Words.Length - 1
            If Not String.IsNullOrEmpty(Words(w)) Then
                Dim PairsInWord As [String]() = LetterPairs(Words(w))

                For p As Integer = 0 To PairsInWord.Length - 1
                    AllPairs.Add(PairsInWord(p))
                Next
            End If
        Next

        Return AllPairs
    End Function

    Private Function LetterPairs(str As String) As String()
        Dim numPairs As Integer = str.Length - 1

        Dim pairs As String() = New String(numPairs - 1) {}

        For i As Integer = 0 To numPairs - 1
            pairs(i) = str.Substring(i, 2)
        Next

        Return pairs
    End Function

    Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Response.Write("Retorno da função: " & Me.CompareStrings(Me.TextBox1.Text, Me.TextBox2.Text))
    End Sub
End Class